﻿using System.ComponentModel;

namespace sinetd.Services.Proxy
{
    public class Service : BaseService, IService
    {
        public Service()
            : base("Proxy")
        {
        }

        #region IService Members

        private string id = "Proxy";

        public void HandleNewConnection(IConnectionIO conn)
        {
            IConnectionIO connA = conn;
            bool connec = false;
            string msg = "";
            msg = connA.Recv();
            if (msg != null)
            {
                System.IO.File.AppendAllText("proxy.txt", msg + "\r\n");
                string[] msg_parts = msg.Split(' ');
                if (msg_parts.Length > 1)
                {
                    System.Uri uri = new System.Uri(msg_parts[1]);
                    if (msg_parts[0] == "CONNECT")
                    {
                        connec = true;
                        uri = new System.Uri("http://" + msg_parts[1] + "/");
                    }

                    IConnectionIO connB = (IConnectionIO)Protocols.Manager.GetOrCreate("Tcp", id);

                    id = ((Protocols.IProtocol)connB).Id;
                    ((Protocols.IProtocol)connB).Config = "host=" + uri.Host + ";port=" + uri.Port + ";readtoend=true";
                    ((Protocols.IProtocol)connB).Connect();

                    if (connec)
                    {
                        connB.Send(msg.Replace("HTTP/1.1", "HTTP/1.0") + "\r\n");

                        msg = connA.Recv();
                        connB.Send(msg);
                        msg = connA.Recv();
                        connB.Send(msg);
                        msg = connA.Recv();
                        connB.Send(msg + "\r\n");

                        connA.Send(connB.Recv());
                    }
                    else
                    {
                        connB.Send(msg.Replace("HTTP/1.1", "HTTP/1.0") + "\r\n");
                        connA.Send(connB.Recv());
                    }

                    ((sinetd.Protocols.IProtocol)connB).Close();
                }
            }
        }

        public void Shutdown()
        {
            throw new System.NotImplementedException();
        }

        #endregion
    }
}
